#-*-coding:utf-8-*-
'''
@ info: post or get request web service!
@ date: 2012-03-06
@ author: huangzy
'''
import urllib,os  
import urllib2 
import sys, httplib
import logClass as log

log = log.Log()

url = 'https://www.graphicmail.cn/api.aspx'

#Username = 'hzy@51094.com'
#Password ='api2012'
Username = 'steventsang@1828.com'
Password ='steven1828'
SID = 37

ADMIN_MAIL = 'steventsang@1828.com'
ADMIN_MAIL_NAME = 'Harvard'

def post(data):  
    '''@post data:return *|*'''
    try:
        data['Username'] = Username
        data['Password'] = Password
        data['SID'] = SID
        req = urllib2.Request(url)  
        data = urllib.urlencode(data)  
        #enable cookie  
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())  
        response = opener.open(req, data)  
        ret = response.read()
        
        if ret[0:1]=='1':
            log.info('【%s】 - 【%s】'%(`data`,ret))
        else:
            log.warn('【%s】 - 【%s】'%(`data`,ret))
        
        return ret
    except Exception,e:
        info = e
        if type(info) != type(''):
            info = str(info)[1:-1]
        log.error('【%s】 - 【%s】'%(`data`,info))
        return e

def get(data):
    '''@get data:return *|*'''
    try:
        data['Username'] = Username
        data['Password'] = Password
        data['SID'] = SID
        data = urllib.urlencode(data)
        full_url = url+'?'+data
        req = urllib2.Request(full_url)
        response = urllib2.urlopen(req)
        ret = response.read()
        
        if ret[0:1]=='1':
            log.info('%s - %s'%(`data`,ret))
        else:
            log.warn('%s - %s'%(`data`,ret))
        
        return ret
    except Exception,e:
        info = e
        if type(info) != type(''):
            info = str(info)[1:-1]
        log.error('【%s】 - 【%s】'%(`data`,info))
        return e

def retsplit(ret):
    '''解析 *|*|* 字符为对象'''
    arr = {}
    if type(ret) != type(''):
        arr['code'] = 0
        arr['info'] = str(ret)[1:-1]
        return arr
    ret = ret.split('|')
    arr['code'] = ret[0]
    arr['info'] = ret[1][0:-1]
    if len(ret)>2:
        arr['other'] = ret[2]
    return arr

def post_create_mailinglist(NewMailinglist=None,ReturnMailingListID='true'): 
    '''创建新的邮寄列表'''
    if NewMailinglist==None:
        NewMailinglist=datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    
    data = {'Function':'post_create_mailinglist','NewMailinglist':NewMailinglist,'ReturnMailingListID':ReturnMailingListID}
    ret = post(data)
    return retsplit(ret)

def  post_import_mailinglist(fileurl,listid,iscsv='false'): 
    '''从 csv, txt, xls or xlsx 格式的文件导入邮件地址到特定邮寄列表'''
    data = {'Function':'post_import_mailinglist','FileUrl':fileurl,'MailinglistID':listid,'IsCsv':iscsv}
    ret = post(data)
    return retsplit(ret)

def post_import_newsletter(HtmlUrl,NewExisting,NewsletterName='',NewsletterID='',ReplaceImages='false',ReplaceLinks='false',TextURL=''):
    data = {'Function':'post_import_newsletter','HtmlURL':HtmlUrl,'NewExisting':NewExisting,'NewsletterID':NewsletterID,'NewsletterName':NewsletterName,'ReplaceImages':ReplaceImages,'ReplaceLinks':ReplaceLinks,'TextURL':TextURL}
    ret = post(data)
    return retsplit(ret)

def post_sendmail(MailinglistID,NewsletterID,Subject,FromEmail=ADMIN_MAIL,FromName=ADMIN_MAIL_NAME,EmbedImages='true',ReturnSendID='true',TextOnly=0):
    data = {'Function':'post_sendmail','MailinglistID':MailinglistID,'EmbedImages':EmbedImages,'NewsletterID':NewsletterID,'Subject':Subject,'FromEmail':FromEmail,'FromName':FromName,'EmbedImages':EmbedImages,'ReturnSendID':ReturnSendID,'TextOnly':TextOnly}
    ret = post(data)
    return retsplit(ret)

def post_delete_mailinglist(MailinglistID):
    data = {'Function':'post_delete_mailinglist','MailinglistID':MailinglistID}
    ret = post(data)
    return retsplit(ret)
  
def post_update_profile(Address1,Address2,ContactEmail,ContactNumber,Name,PostalCode,Surname,CountryID=86,Organization='',WebsiteUrl=''):
    data = {
        'Function':'post_update_profile',
        'Address1':Address1,
        'Address2':Address2,
        'ContactEmail':ContactEmail,
        'ContactNumber':ContactNumber,
        'CountryID':CountryID,
        'Name':Name,
        'PostalCode':PostalCode,
        'Surname':Surname,
        'Organization':Organization,
        'WebsiteUrl':WebsiteUrl
    }
    ret = post(data)
    return retsplit(ret)

def post_delete_newsletter(NewsletterID):
    '''删除指定的邮件快讯'''
    data = {'Function':'post_delete_newsletter','NewsletterID':NewsletterID}
    ret = post(data)
    return retsplit(ret)

def get_mailinglist(MailinglistID,Status='OK',CsvFormat='0'):
    '''
        返回特定邮寄列表中所有的邮件地址
        @status HB = 硬退回 OK = 可用的 S = 已订阅 S2 = 双重选择确认 SP = 双重选择未确认 U = 退订的
    '''
    data = {'Function':'get_mailinglist','MailinglistID':MailinglistID,'Status':Status,'CsvFormat':CsvFormat}
    return get(data)

def get_mailinglists (MailinglistCount=None):
    '''返回账户中所有的邮寄列表'''
    if MailinglistCount==None:
        data = data = {'Function':'get_mailinglists'}
    else:
        data = {'Function':'get_mailinglists','MailinglistCount':MailinglistCount}
    return get(data)

def get_newsletter(NewsletterID,TextVersion='false'):
    '''返回账户中指定的邮寄列表'''
    data = {'Function':'get_newsletter','NewsletterID':NewsletterID,'TextVersion':TextVersion}
    return get(data)

def get_newsletters():
    '''返回账户中所有的邮寄列表'''
    data = {'Function':'get_newsletters'}
    return get(data)

def get_bounced(SendID,FromDate='',ToDate=''):
    '''根据特定的发送编号或者特定的日期范围返回一个反弹回来的邮件地址列表'''
    data = {'Function':'get_bounced','SendID':SendID,'FromDate':FromDate,'ToDate':ToDate}
    return get(data)

def get_delivered(SendID):
    '''根据发送编号统计某次发送中成功投递的邮箱信息'''
    data = {'Function':'get_delivered','SendID':SendID}
    return get(data)


if __name__ == '__main__':
    maillist = get_delivered(1348489870945)
    print maillist

    #print post_delete_mailinglist(36295)
